<?php

namespace app\storeapi\model;
use app\storeapi\model\Wxapp AS WxappModel;
use app\common\library\wechat\WxUser;
use app\common\exception\BaseException;
use app\common\model\User as UserModel;
use app\api\model\dealer\Referee as RefereeModel;
use app\api\model\dealer\Setting as DealerSettingModel;
use app\admin\model\BaseSetting as SettingModel;
use app\storeapi\model\store\User as StoreUser;
use app\storeapi\model\store\Clerk as ClerkUser;
use org\Redis;




/**
 *登录模型类
 * Class User
 * @package app\storeapi\model
 */
class User extends Base
{
    /* @ver $token 小程序令牌 */
    private $token;

    /**
     * 用户登录
     * @param array $post
     * @return string
     * @throws BaseException
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function login($post)
    {
        $login_user_id = $post['login_user_id'];
        $identity = $post['identity'];
        // 微信登录 获取session_key
        //$session = $this->wxlogin1($post['code'],self::$wxapp_id);
        $session = $this->wxlogin1($post['code']);
        // 自动注册用户
        $refereeId = isset($post['referee_id']) ? $post['referee_id'] : null;
        $userInfo = $post['user_info'];
        $user_id = $this->register($session['openid'], $userInfo, $refereeId);
        // 生成token (session3rd)
        $this->token = $this->token($session['openid'],$login_user_id,$identity);
        // 记录缓存, 7天
      	$redis = new Redis();
        $tokenData = ['user_id'=>$user_id,'openid'=>$session['openid'],'login_user_id'=>$login_user_id,'identity'=>$identity];
        $redis->set($this->token,$tokenData,86400 * 7);

        return ['token'=>$this->token,'wxapp_id'=>self::$wxapp_id,'identity'=>$identity];
    }
    /*
     * 修改用户信息
     */
    public function updateData($data){
        if(empty($data)){
            throw new BaseException(['msg' => '参数不能为空']);
        }
        if($this->where(['user_id'=>$data['user_id']])->update($data)){
            return ['code'=>'success'];
        }
        return ['code'=>'error'];
    }
    /**
     * 自动注册用户
     * @param $open_id
     * @param $data
     * @param int $refereeId
     * @return mixed
     * @throws \Exception
     * @throws \think\exception\DbException
     */
    private function register($open_id, $data, $refereeId = null)
    {

        // 查询用户是否已存在
        $user = (new UserModel)::detail(['open_id' => $open_id]);
        $model = $user ?: new UserModel;
        $this->startTrans();
        try {
            // 保存/更新用户记录
            if (!$model->allowField(true)->save(array_merge($data, [
                'open_id' => $open_id,
                'wxapp_id' => 0,
            ]))) {
                throw new BaseException(['msg' => '用户注册失败']);
            }
            // 记录推荐人关系
            if (!$user && $refereeId > 0) {
                RefereeModel::createRelation($model['user_id'], $refereeId);
            }
            $this->commit();
        } catch (\Exception $e) {
            $this->rollback();
            throw new BaseException(['msg' => $e->getMessage()]);
        }
        return $model['user_id'];
    }


    /**
     * 获取token
     * @return mixed
     */
    public function getToken()
    {
        return $this->token;
    }

    /**
     * 微信登录
     * @param $code
     * @return array|mixed
     * @throws BaseException
     * @throws \think\exception\DbException
     */
    private function wxlogin1($code)
    {
        $wxConfig = SettingModel::getItem('wechat');
        // 验证appid和appsecret是否填写
        if (empty($wxConfig['app_id']) || empty($wxConfig['app_secret'])) {
            throw new BaseException(['msg' => self::ERROR_MSG_BASE]);
        }
        // 微信登录 (获取session_key)
        $WxUser = new WxUser($wxConfig['app_id'], $wxConfig['app_secret']);
        if (!$session = $WxUser->sessionKey($code)) {
            throw new BaseException(['msg' => $WxUser->getError()]);
        }
        return $session;
    }

    /**
     * 微信登录
     * @param $code
     * @return array|mixed
     * @throws BaseException
     * @throws \think\exception\DbException
     */
//    private function wxlogin($code,$wxapp_id)
//    {
//
//        $model = new WxappModel();
//        // 获取当前小程序信息
//        $wxConfig = $model::getWxappInfo($wxapp_id);
//        // 验证appid和appsecret是否填写
//        if (empty($wxConfig['app_id']) || empty($wxConfig['app_secret'])) {
//            throw new BaseException(['msg' => self::ERROR_MSG_BASE]);
//        }
//        // 微信登录 (获取session_key)
//        $WxUser = new WxUser($wxConfig['app_id'], $wxConfig['app_secret']);
//        if (!$session = $WxUser->sessionKey($code)) {
//            throw new BaseException(['msg' => $WxUser->getError()]);
//        }
//        return $session;
//    }

    /**
     * 生成用户认证的token
     * @param $openid
     * @return string
     */
    private function token($openid,$login_user_id,$identity)
    {
        $wxapp_id = self::$wxapp_id;
        // 生成一个不会重复的随机字符串
        $guid = \getGuidV4();
        // 当前时间戳 (精确到毫秒)
        $timeStamp = microtime(true);
        // 自定义一个盐
        $salt = 'store_salt_token';
        return md5("{$wxapp_id}_{$timeStamp}_{$openid}_{$guid}_{$login_user_id}_{$identity}_{$salt}");
    }


    /**
     * 获取用户信息
     * @param $where
     * @param $with
     * @return null|static
     * @throws \think\exception\DbException
     */
    public static function detail($where)
    {

        $filter = ['is_delete' => 0];
        if (is_array($where)) {
            $filter = array_merge($filter, $where);
        } else {
            $filter['user_id'] = (int)$where;
        }
        return static::get($filter);
    }


    /**
     * 获取用户列表
     * @param $where
     * @param $with
     * @return null|static
     * @throws \think\exception\DbException
     */
    public function userList($data)
    {
        // 商品列表获取条件
        $param = array_merge([
            'search' => '',         // 搜索关键词
        ], $data);
        // 筛选条件
        $filter = [];
        $filter['wxapp_id'] = $param['wxapp_id'];
        $filter['is_delete'] = 0;
        !empty($param['search']) && $filter['nickName'] = ['like', '%' . trim($param['search']) . '%'];

        $page = isset($param['page']) && is_numeric($param['page']) ? intval($param['page']) : 1;
        $limit = 15;
        $offset = ($page - 1) * $limit;

        $list = $this->where($filter)
            ->order(['create_time' => 'desc'])
            ->field('user_id,open_id,nickName,avatarUrl')
            ->limit($offset, $limit)
            ->select();
        return $list;
    }



}
